package utils

import (
	"bytes"
	"fmt"
	"path/filepath"
	"time"

	"cashway.com/cis/assistant/config"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	logrus "github.com/sirupsen/logrus"
)

type LogFormatter struct{}

func (m *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	var buffer *bytes.Buffer
	if entry.Buffer != nil {
		buffer = entry.Buffer
	} else {
		buffer = &bytes.Buffer{}
	}

	timestamp := entry.Time.Format("2006-01-02 15:04:05.000")
	var newLog = fmt.Sprintf("%s [%s] %s\n", timestamp, entry.Level, entry.Message)

	buffer.WriteString(newLog)
	return buffer.Bytes(), nil
}

func init() {
	linkFileName := filepath.Join(config.Config.LogsPath, config.Config.LogLinkName)
	logFileName := filepath.Join(config.Config.LogsPath, config.Config.LogNamePattern)

	writer, err := rotatelogs.New(
		logFileName,
		rotatelogs.WithLinkName(linkFileName),
		rotatelogs.WithMaxAge(time.Duration(config.Config.LogSaveMaxAge)*time.Second),
		rotatelogs.WithRotationTime(time.Duration(config.Config.RotationTime)*time.Second),
		rotatelogs.WithRotationSize(config.Config.RotationSize),
	)
	if err != nil {
		fmt.Println("create rotatelogs faild.")
		return
	}
	logrus.SetOutput(writer)
	logrus.SetFormatter(&LogFormatter{})
}
